//
//	 ______    ______    ______
//	/\  __ \  /\  ___\  /\  ___\
//	\ \  __<  \ \  __\_ \ \  __\_
//	 \ \_____\ \ \_____\ \ \_____\
//	  \/_____/  \/_____/  \/_____/
//
//
//	Copyright (c) 2014-2015, Geek Zoo Studio
//	http://www.bee-framework.com
//
//
//	Permission is hereby granted, free of charge, to any person obtaining a
//	copy of this software and associated documentation files (the "Software"),
//	to deal in the Software without restriction, including without limitation
//	the rights to use, copy, modify, merge, publish, distribute, sublicense,
//	and/or sell copies of the Software, and to permit persons to whom the
//	Software is furnished to do so, subject to the following conditions:
//
//	The above copyright notice and this permission notice shall be included in
//	all copies or substantial portions of the Software.
//
//	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
//	FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
//	IN THE SOFTWARE.
//

#if (TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR)

#import "Bee_UIApplication.h"
#import "Bee_UIRouter.h"

//#import "WeiboApi.h"
//#import "XGPush.h"
#import "EaseMob.h"
#import "MobClick.h"
#pragma mark -

DEF_PACKAGE( BeePackage_UI, BeeUIApplication, application );

#pragma mark -

@interface BeeUIApplication()
{
    BOOL		_ready;
    NSUInteger	_device;
    UIWindow *	_window;
    CLLocationManager *location;
}

- (void)initWindow;

@end

#pragma mark -

@implementation BeeUIApplication

DEF_NOTIFICATION( LAUNCHED )		// did launched
DEF_NOTIFICATION( TERMINATED )		// will terminate
DEF_NOTIFICATION( WILLENTERFOREGROUND )		//APP打开的时候  先home切出去在切进来

DEF_NOTIFICATION( STATE_CHANGED )	// state changed
DEF_NOTIFICATION( MEMORY_WARNING )	// memory warning

DEF_NOTIFICATION( LOCAL_NOTIFICATION )
DEF_NOTIFICATION( REMOTE_NOTIFICATION )

DEF_NOTIFICATION( APS_REGISTERED )
DEF_NOTIFICATION( APS_ERROR )

DEF_INT( DEVICE_CURRENT,		0 )
DEF_INT( DEVICE_PHONE_3_INCH,	1 )
DEF_INT( DEVICE_PHONE_4_INCH,	2 )

@synthesize ready = _ready;
@synthesize window = _window;
@dynamic device;
@dynamic inForeground;
@dynamic inBackground;

static BeeUIApplication * __sharedApp = nil;

+ (BeeUIApplication *)sharedInstance
{
    return __sharedApp;
}

- (void)load
{
    
}

- (void)unload
{
    
}

- (id)init
{
    self = [super init];
    if ( self )
    {
        //		[self load];
        //		[self performLoad];
    }
    return self;
}

- (void)dealloc
{
    //	[self unload];
    [self performUnload];
    
    [_window release];
    _window = nil;
    
    [super dealloc];
}

#pragma mark -

- (BOOL)inForeground
{
    UIApplicationState state = [UIApplication sharedApplication].applicationState;
    if ( UIApplicationStateActive == state )
    {
        return YES;
    }
    
    return NO;
}

- (BOOL)inBackground
{
    return [self inForeground] ? NO : YES;
}

#pragma mark -

- (void)initWindow
{
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    self.window.alpha = 1.0f;
    //	self.window.layer.masksToBounds = YES;
    //	self.window.layer.opaque = YES;
    self.window.backgroundColor = [UIColor clearColor];
}

- (void)applySimulation
{
    CGRect phoneFrame = [[UIScreen mainScreen] bounds];
    
    if ( [BeeSystemInfo isPadRetina] || [BeeSystemInfo isPad] )
    {
        if ( self.DEVICE_PHONE_3_INCH == _device )
        {
            phoneFrame.size.width = 640.0f;
            phoneFrame.size.height = 960.0f;
        }
        else if ( self.DEVICE_PHONE_4_INCH == _device )
        {
            phoneFrame.size.width = 640.0f;
            phoneFrame.size.height = 1136.0f;
        }
        
        if ( [BeeSystemInfo isPad] )
        {
            phoneFrame.size.width /= 2.0f;
            phoneFrame.size.height /= 2.0f;
        }
    }
    
    phoneFrame.origin.x = ([UIScreen mainScreen].bounds.size.width - phoneFrame.size.width) / 2.0f;
    phoneFrame.origin.y = ([UIScreen mainScreen].bounds.size.height - phoneFrame.size.height) / 2.0f;
    
    self.window.frame = phoneFrame;
}

- (NSUInteger)device
{
    return _device;
}

- (void)setDevice:(NSUInteger)d
{
    if ( d != _device )
    {
        _device = d;
        
        if ( _ready )
        {
            [self applySimulation];
        }
    }
}


- (void)registerRemoteNotification{
#if !TARGET_IPHONE_SIMULATOR
    UIApplication *application = [UIApplication sharedApplication];
    application.applicationIconBadgeNumber = 0;
    
    //iOS8 注册APNS
    if ([application respondsToSelector:@selector(registerForRemoteNotifications)]) {
        [application registerForRemoteNotifications];
        UIUserNotificationType notificationTypes = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:notificationTypes categories:nil];
        [application registerUserNotificationSettings:settings];
    }else{
        UIRemoteNotificationType notificationTypes = UIRemoteNotificationTypeBadge |
        UIRemoteNotificationTypeSound |
        UIRemoteNotificationTypeAlert;
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:notificationTypes];
    }
#endif
    
}

#pragma mark -


- (void)applicationDidFinishLaunching:(UIApplication *)application
{
    [self application:application didFinishLaunchingWithOptions:nil];
}


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *dir = [path stringByAppendingPathComponent:@"SandBoxphoto"];
    NSFileManager *filem = [[NSFileManager alloc]init];
    BOOL isdir = YES;
    [filem removeItemAtPath:dir error:nil];
    if (![filem fileExistsAtPath:dir isDirectory:&isdir]) {
        if ([filem createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil]) {
            NSLog(@"创建成功");
        }else{
            NSLog(@"创建失败");
        }
    }
// 真机的情况下,notification提醒设置
    [self registerRemoteNotification];
    //注册 APNS文件的名字, 需要与后台上传证书时的名字一一对应
//    [[EaseMob sharedInstance]registerSDKWithAppKey:@"dingding#dd" apnsCertName:@"dd_develop"];
    [[EaseMob sharedInstance]registerSDKWithAppKey:@"dingding#dd" apnsCertName:@"dd_production"];
    
    
    [[EaseMob sharedInstance]application:application didFinishLaunchingWithOptions:launchOptions];

    [[UINavigationBar appearance]setBackgroundImage:[UIImage imageNamed:@"title.png"] forBarMetrics:UIBarMetricsDefault];
    location = [[CLLocationManager alloc]init];
    location.delegate=self;
    [self  startTrackingLocation];
    //    [MobClick startWithAppkey:@"5389bb7f56240ba94208ac97"
    //                 reportPolicy:BATCHg
    //                    channelId:Nil];
    [MobClick setLogEnabled:YES];  // 打开友盟sdk调试，注意Release发布时需要注释掉此行,减少io消耗
    [MobClick startWithAppkey:@"53bf9bab56240b753300a61c" reportPolicy:(ReportPolicy) REALTIME channelId:@"test1001"];
    __sharedApp = self;
    
    [self initWindow];
    //	[self load];
    [self performLoad];
    if ( nil == self.window.rootViewController )
    {
        self.window.rootViewController = [BeeUIRouter sharedInstance];
    }
    
    if ( self.window.rootViewController )
    {
        UNUSED( self.window.rootViewController.view );
        
    }
    
    [self.window makeKeyAndVisible];
    
    //	[self applySimulation];
    
    if ( nil != launchOptions ) // 从通知启动
    {
        NSURL *		url = [launchOptions objectForKey:UIApplicationLaunchOptionsURLKey];
        NSString *	bundleID = [launchOptions objectForKey:UIApplicationLaunchOptionsSourceApplicationKey];
        
        if ( url || bundleID )
        {
            NSMutableDictionary * params = [NSMutableDictionary dictionary];
            params.APPEND( @"url", url );
            params.APPEND( @"source", bundleID );
            
            [self postNotification:BeeUIApplication.LAUNCHED withObject:params];
        }
        else
        {
            [self postNotification:BeeUIApplication.LAUNCHED];
        }
        
        UILocalNotification * localNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
        if ( localNotification )
        {
            NSDictionary * dict = [NSDictionary dictionaryWithObjectsAndKeys:localNotification.userInfo, @"userInfo", [NSNumber numberWithBool:NO], @"inApp", nil];
            [self postNotification:BeeUIApplication.LOCAL_NOTIFICATION withObject:dict];
        }
        
        NSDictionary * remoteNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
        if ( remoteNotification )
        {
            NSDictionary * dict = [NSDictionary dictionaryWithObjectsAndKeys:remoteNotification, @"userInfo", [NSNumber numberWithBool:NO], @"inApp", nil];
            [self postNotification:BeeUIApplication.REMOTE_NOTIFICATION withObject:dict];
        }
    }
    else
    {
        [self postNotification:BeeUIApplication.LAUNCHED];
    }
    
    _ready = YES;
    return YES;
}

// Will be deprecated at some point, please replace with application:openURL:sourceApplication:annotation:
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    return [self application:application openURL:url sourceApplication:nil annotation:nil];
}

// no equiv. notification. return NO if the application can't open for some reason
//- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
//{
//    	if ( url || sourceApplication )
//    	{
//    		NSMutableDictionary * params = [NSMutableDictionary dictionary];
//    		params.APPEND( @"url", url );
//    		params.APPEND( @"source", sourceApplication );
//
//    		[self postNotification:BeeUIApplication.LAUNCHED withObject:params];
//
//    	}
//    	else
//    	{
//    		[self postNotification:BeeUIApplication.LAUNCHED];
//    	}
//
//}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // 让SDK得到App目前的各种状态，以便让SDK做出对应当前场景的操作
    [[EaseMob sharedInstance] applicationDidBecomeActive:application];
    [self.window.rootViewController viewWillAppear:NO];
    [self.window.rootViewController viewDidAppear:NO];
    
    [self postNotification:BeeUIApplication.STATE_CHANGED];
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // 让SDK得到App目前的各种状态，以便让SDK做出对应当前场景的操作
    [[EaseMob sharedInstance] applicationWillResignActive:application];
    [self.window.rootViewController viewWillDisappear:NO];
    [self.window.rootViewController viewDidDisappear:NO];
    
    [self postNotification:BeeUIApplication.STATE_CHANGED];
}

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application
{
    [self postNotification:BeeUIApplication.MEMORY_WARNING];
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // 让SDK得到App目前的各种状态，以便让SDK做出对应当前场景的操作
    [[EaseMob sharedInstance] applicationWillTerminate:application];
    [self postNotification:BeeUIApplication.TERMINATED];
}

#pragma mark -

- (void)application:(UIApplication *)application willChangeStatusBarOrientation:(UIInterfaceOrientation)newStatusBarOrientation duration:(NSTimeInterval)duration
{
    
}

- (void)application:(UIApplication *)application didChangeStatusBarOrientation:(UIInterfaceOrientation)oldStatusBarOrientation
{
    
}

- (void)application:(UIApplication *)application willChangeStatusBarFrame:(CGRect)newStatusBarFrame
{
    
}

- (void)application:(UIApplication *)application didChangeStatusBarFrame:(CGRect)oldStatusBarFrame
{
    
}

#pragma mark - Location

- (void)startTrackingLocation {
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
    if (status == kCLAuthorizationStatusNotDetermined) {
        [location requestAlwaysAuthorization];
    }
    else if (status == kCLAuthorizationStatusAuthorizedWhenInUse || status == kCLAuthorizationStatusAuthorizedAlways) {
        [location startUpdatingLocation];
    }
}

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    switch (status) {
        case kCLAuthorizationStatusAuthorizedAlways:
        case kCLAuthorizationStatusAuthorizedWhenInUse:
            NSLog(@"Got authorization, start tracking location");
            [self startTrackingLocation];
            break;
        case kCLAuthorizationStatusNotDetermined:
            [location requestAlwaysAuthorization];
        default:
            break;
    }
}

- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation{
    NSString *strlat = [NSString stringWithFormat:@"%f",newLocation.coordinate.latitude];
    NSString *strlng = [NSString stringWithFormat:@"%f",newLocation.coordinate.longitude];
    NSLog(@"%@----%@",strlat,strlng);
    [[NSUserDefaults standardUserDefaults]setObject:strlat forKey:@"lat"];
    [[NSUserDefaults standardUserDefaults]setObject:strlng forKey:@"lnt"];
    [[NSUserDefaults standardUserDefaults]synchronize];
    [location stopUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    NSLog(@"%@",error);
}
- (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray *)locations{
    
    CLLocation *ca = [locations firstObject];
    [[NSUserDefaults standardUserDefaults]setObject:[NSString stringWithFormat:@"%f",ca.coordinate.latitude] forKey:@"lat"];
    [[NSUserDefaults standardUserDefaults]setObject:[NSString stringWithFormat:@"%f",ca.coordinate.longitude] forKey:@"lnt"];
    [[NSUserDefaults standardUserDefaults]synchronize];
    NSLog(@"%@",ca);
    [location stopUpdatingLocation];
}


#pragma mark -

// one of these will be called after calling -registerForRemoteNotifications
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    
    //    NSString * deviceTokenStr = [XGPush registerDevice: deviceToken];
    
    //打印获取的deviceToken的字符串
    //    NSLog(@"deviceTokenStr is %@",deviceTokenStr);
    //向信鸽提交token
    //    NSLog(@"deviceToken:%@",deviceToken);
    //    [XGPush registerDevice:deviceToken];
    
    [[EaseMob sharedInstance]application:application didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
    
    //    NSString * token = [deviceToken description];
    //    token = [token stringByReplacingOccurrencesOfString:@"<" withString:@""];
    //    token = [token stringByReplacingOccurrencesOfString:@">" withString:@""];
    //    token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
    //    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    //    [[NSUserDefaults standardUserDefaults] setObject:token forKey:@"token"];
    //    [userDefaults synchronize];
    //
    //    [self postNotification:BeeUIApplication.APS_REGISTERED withObject:token];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"注册推送失败"
                                                    message:error.description
                                                   delegate:nil
                                          cancelButtonTitle:@"确定"
                                          otherButtonTitles:nil];
    [alert show];
    [self postNotification:BeeUIApplication.APS_ERROR withObject:error];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    
    //    [XGPush handleReceiveNotification:userInfo];
    NSLog(@"userinfo is %@----%@",userInfo,[[userInfo objectForKey:@"aps"]objectForKey:@"alert"]);
    UIApplicationState state = [UIApplication sharedApplication].applicationState;
    if ( UIApplicationStateInactive == state || UIApplicationStateBackground == state )
    {
        NSDictionary * dict = [NSDictionary dictionaryWithObjectsAndKeys:userInfo, @"userInfo", [NSNumber numberWithBool:NO], @"inApp", nil];
        [self postNotification:BeeUIApplication.REMOTE_NOTIFICATION withObject:dict];
    }
    else
    {
        NSDictionary * dict = [NSDictionary dictionaryWithObjectsAndKeys:userInfo, @"userInfo", [NSNumber numberWithBool:YES], @"inApp", nil];
        [self postNotification:BeeUIApplication.REMOTE_NOTIFICATION withObject:dict];
    }
}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
    
    //notification是发送推送时传入的字典信息
    //    [XGPush localNotificationAtFrontEnd:notification userInfoKey:@"clockID" userInfoValue:@"myid"];
    
    //    删除推送列表中的这一条
    //    [XGPush delLocalNotification:notification];
    //[XGPush delLocationNotification:@"clockID" userInfoValue:@"myid"];
    
    //清空推送列表
    //[XGPush clearLocalNotifications];
    
    NSLog(@"local userinfo is %@--body:%@",notification.userInfo,notification.alertBody);
    
    UIApplicationState state = [UIApplication sharedApplication].applicationState;
    if ( UIApplicationStateInactive == state || UIApplicationStateBackground == state )
    {
        NSDictionary * dict = [NSDictionary dictionaryWithObjectsAndKeys:notification.userInfo, @"userInfo", [NSNumber numberWithBool:NO], @"inApp", nil];
        [self postNotification:BeeUIApplication.LOCAL_NOTIFICATION withObject:dict];
    }
    else
    {
        NSDictionary * dict = [NSDictionary dictionaryWithObjectsAndKeys:notification.userInfo, @"userInfo", [NSNumber numberWithBool:YES], @"inApp", nil];
        [self postNotification:BeeUIApplication.LOCAL_NOTIFICATION withObject:dict];
    }
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // 让SDK得到App目前的各种状态，以便让SDK做出对应当前场景的操作
    [[EaseMob sharedInstance] applicationDidEnterBackground:application];
    [self postNotification:BeeUIApplication.STATE_CHANGED];
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // 让SDK得到App目前的各种状态，以便让SDK做出对应当前场景的操作
    [[EaseMob sharedInstance] applicationWillEnterForeground:application];
    [self postNotification:BeeUIApplication.STATE_CHANGED];
    [self postNotification:BeeUIApplication.WILLENTERFOREGROUND];
    
}

- (void)applicationProtectedDataWillBecomeUnavailable:(UIApplication *)application
{
}

- (void)applicationProtectedDataDidBecomeAvailable:(UIApplication *)application
{
}


@end

#endif	// #if (TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR)

